﻿#include "purchaselog.h"
#include "ui_purchaselog.h"

PurchaseLog::PurchaseLog(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::PurchaseLog)
{
    ui->setupUi(this);

    table=TD_PURCHASE_LOG;
    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::DoubleClicked);

    updateCategory();
    createMenu();
    updateTodayView();
}

PurchaseLog::~PurchaseLog()
{
    delete ui;
}

void PurchaseLog::updateView()
{
    if(!selectCategory.isEmpty())
    {
        model->setTable(table);
        model->setFilter(QString("category = '%1'").arg(selectCategory));
        model->select();
        setHeaderData();
    }
    else
        updateTodayView();
}

void PurchaseLog::generateMenu()
{
    menu->addAction(QStringLiteral("打开链接 (Alt+W)"),this,&PurchaseLog::openUrl);
    menu->addSeparator();
    menu->addAction(QStringLiteral("更新类别 (F4)"),this,&PurchaseLog::updateCategory);
    menu->addAction(QStringLiteral("今日记录"),this,&PurchaseLog::updateTodayView);
    menu->addAction(QStringLiteral("快件跟进"),this,&PurchaseLog::do_addTrack);
    menu->addSeparator();
    menu->addAction(QStringLiteral("空白新增 (F1)"),this,&PurchaseLog::newItem);
    menu->addAction(QStringLiteral("复制新增 (F2)"),this,&PurchaseLog::copyNewItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("撤销 (Ctrl+Z)"),this,&PurchaseLog::revert);
    menu->addAction(QStringLiteral("保存 (Ctrl+S)"),this,&PurchaseLog::save);
    menu->addSeparator();
    QMenu *m_option=menu->addMenu(QStringLiteral("选项"));
    m_option->addAction(QStringLiteral("生成记录"),this,&PurchaseLog::generateSummary);
    m_option->addSeparator();
    m_option->addAction(QStringLiteral("删除 (Delete)"),this,&PurchaseLog::removeItem);
}

void PurchaseLog::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::AltModifier && event->key() == Qt::Key_W)
        openUrl();
    else if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_S)
        save();
    else if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Z)
        revert();
    else
    {
        switch (event->key()) {
        case Qt::Key_F1:
            newItem();
            break;
        case Qt::Key_F2:
            copyNewItem();
            break;
        case Qt::Key_F4:
            updateCategory();
            break;
        case Qt::Key_Delete:
            removeItem();
            break;
        }
    }
}

void PurchaseLog::openUrl()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    QString url=index.sibling(index.row(),9).data().toString();
    if(!url.isEmpty())
        QDesktopServices::openUrl(QUrl(url));
}

void PurchaseLog::copyNewItem()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    QString topic=index.sibling(index.row(),2).data().toString();
    QString label=index.sibling(index.row(),3).data().toString();
    if(topic.isEmpty() || label.isEmpty())
        return;

    QString model=index.sibling(index.row(),4).data().toString();
    QString material=index.sibling(index.row(),5).data().toString();
    QString url=index.sibling(index.row(),9).data().toString();

    PL_AddItem itemAdd;
    itemAdd.move(x() + 100,y() + 50);
    itemAdd.setItem(topic,label,model,material,url);
    if(itemAdd.exec() == QDialog::Accepted)
        updateView();
}

void PurchaseLog::newItem()
{
    PL_AddItem itemAdd;
    if(!selectCategory.isEmpty())
    {
        itemAdd.setCategory(selectCategory);
    }
    itemAdd.move(x() + 100,y() + 50);
    if(itemAdd.exec() == QDialog::Accepted)
    {
        updateCategory();
        if(categories.contains(selectCategory))
            updateView();
    }
}

void PurchaseLog::removeItem()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(index.isValid())
        model->removeRow(index.row());
}

void PurchaseLog::updateCategory()
{
    if(!categories.isEmpty())
        categories.clear();

    categories=sp_getCategory(table);
    listModel->setStringList(categories);
}

void PurchaseLog::updateTodayView()
{
    if(!selectCategory.isEmpty())
        selectCategory.clear();

    model->setTable(table);
    model->setFilter(QString("date_ = '%1'").arg(Today));
    model->select();
    setHeaderDataL();
}

void PurchaseLog::setHeaderDataL()
{
    ui->tableView->hideColumn(0);   //id
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("日期"));   //date
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("类别"));   //category
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("名称"));    //label
    ui->tableView->setColumnWidth(3,200);
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("型号"));    //model
    model->setHeaderData(5,Qt::Horizontal,QStringLiteral("材质"));    //material
    model->setHeaderData(6,Qt::Horizontal,QStringLiteral("数量"));    //number
    model->setHeaderData(7,Qt::Horizontal,QStringLiteral("单价"));    //price
    model->setHeaderData(8,Qt::Horizontal,QStringLiteral("总价"));    //total
    ui->tableView->hideColumn(9);   //url
    model->setHeaderData(10,Qt::Horizontal,QStringLiteral("备注"));    //remark
}

void PurchaseLog::setHeaderData()
{
    ui->tableView->hideColumn(0);   //id
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("日期"));   //date
    ui->tableView->hideColumn(2);   //category
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("名称"));    //label
    ui->tableView->setColumnWidth(3,200);
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("型号"));    //model
    model->setHeaderData(5,Qt::Horizontal,QStringLiteral("材质"));    //material
    model->setHeaderData(6,Qt::Horizontal,QStringLiteral("数量"));    //number
    model->setHeaderData(7,Qt::Horizontal,QStringLiteral("单价"));    //price
    model->setHeaderData(8,Qt::Horizontal,QStringLiteral("总价"));    //total
    ui->tableView->hideColumn(9);   //url
    model->setHeaderData(10,Qt::Horizontal,QStringLiteral("备注"));    //remark
}

void PurchaseLog::do_addTrack()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    QString label=sp_fetchString(index,3);
    int number=sp_fetchData(index,6).toInt();
    QSqlQuery query;
    query.prepare(QString("insert into %1 (date_,label,addition) "
                          "values (?,?,?)")
                  .arg(TD_EXPRESS_TRACK));
    query.addBindValue(Today);
    query.addBindValue(label + " " + QString::number(number));
    query.addBindValue("开始跟进");
    if(query.exec())
        QMessageBox::information(this,"操作已完成",
                                 "操作已完成,记录已添加。");
    else
    {
        qDebug() << query.lastError().text();
        QMessageBox::warning(this,"操作未完成",
                             "操作未完成,记录无法添加！");
    }
}

void PurchaseLog::on_keyword_returnPressed()
{
    QString kw=ui->keyword->text().trimmed();
    if(kw.isEmpty())
        return;

    model->setTable(table);
    model->setFilter(QString("label like '%%1%'")
                     .arg(kw));
    model->select();
    setHeaderDataL();
}

void PurchaseLog::generateSummary()
{
    QSqlQuery query;
    query.exec(QString("SELECT label,model,number FROM %1 WHERE date_='%2'")
               .arg(table)
               .arg(Today));
    QStringList items;
    items.append(Today + QStringLiteral(" 采购记录："));
    while(query.next())
    {
        QString label=query.value(0).toString();
        if(label.isEmpty())
            continue;

        QString model=query.value(1).toString();

        int i_number=query.value(2).toInt();
        if(i_number == 0)
            continue;

        QString number=QString::number(i_number);
        QString item=label + QString(" ") +model + QStringLiteral(" 已采购 ") + number;
        items.append(item);
    }

    if(!items.isEmpty())
    {
        QString summary=items.join("\n");
        qApp->clipboard()->setText(summary);
    }
    else
        qApp->clipboard()->setText(QStringLiteral("今日未采购！"));
}

void PurchaseLog::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectCategory=index.data().toString();
        updateView();
    }
}
